package com.demo.maintenance.activity;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.demo.maintenance.R;
import com.demo.maintenance.bean.SummaryBean;
import com.demo.maintenance.contant.Global;
import com.demo.maintenance.utils.AntiShakeUtils;
import com.demo.maintenance.utils.HttpManager;
import com.demo.maintenance.utils.PermissionUtils;
import com.demo.maintenance.utils.SystemBarTintManager;
import com.demo.maintenance.utils.TimeUtils;
import com.google.android.material.floatingactionbutton.FloatingActionButton;
import com.hjq.toast.ToastUtils;
import com.kongzue.dialogx.dialogs.WaitDialog;
import com.qmuiteam.qmui.util.QMUIStatusBarHelper;
import com.uuzuche.lib_zxing.activity.CaptureActivity;
import com.uuzuche.lib_zxing.activity.CodeUtils;

import java.util.ArrayList;
import java.util.List;

public class SummaryListActivity extends AppCompatActivity {

    private RecyclerView recycler_view;
    private ListAdapter listAdapter;
    private List<SummaryBean.Data> datasource = new ArrayList<>();
    private FloatingActionButton btn_create;
    private final int RESULT_CODE = 201;
    private SummaryBean.Data clickItem;

    @Override
    protected void onResume() {
        super.onResume();
        requestData();
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        QMUIStatusBarHelper.translucent(this);
        SystemBarTintManager.setStatusBarDarkTheme(this, true);
        setContentView(R.layout.activity_list_summary);

        findViewById(R.id.common_back_iv).setOnClickListener(v -> finish());
        ((TextView) findViewById(R.id.common_content_tv)).setText("Summary List");

        btn_create = findViewById(R.id.btn_create);
        btn_create.setOnClickListener(v -> {
            if (AntiShakeUtils.isInvalidClick(v)) {
                return;
            }
            startActivity(new Intent(SummaryListActivity.this, SummaryUploadActivity.class));
        });

        btn_create.setVisibility(!"guardian".equals(Global.userResponse.data.role) ? View.VISIBLE : View.GONE);

        listAdapter = new ListAdapter();
        recycler_view = findViewById(R.id.recycler_view);
        recycler_view.setLayoutManager(new LinearLayoutManager(this));
        recycler_view.setAdapter(listAdapter);
    }

    private void requestData() {

        WaitDialog.show("Waiting");

        String url = Global.ipAddress + "/system/summary/listAll?phone=" + Global.userResponse.data.userPhone;

        try {
            HttpManager.get(url, new HttpManager.NetworkCallBack() {
                @Override
                public void onSuccess(String successInfo) {
                    try {
                        Log.e("monitoring", successInfo);

                        SummaryBean assignmentBean = JSON.parseObject(successInfo, SummaryBean.class);
                        if (assignmentBean.code == 200) {
                            runOnUiThread(() -> {
                                if (assignmentBean.rows != null && !assignmentBean.rows.isEmpty()) {
                                    datasource.clear();
                                    datasource.addAll(assignmentBean.rows);
                                    listAdapter.notifyDataSetChanged();
                                }
                            });
                        } else {

                            Log.e("monitoring", "get list failed !");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(String errorInfo) {
                    Log.e("monitoring", errorInfo);
                }

                @Override
                public void onFinal() {
                    super.onFinal();
                    WaitDialog.dismiss();
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            WaitDialog.dismiss();
        }
    }

    private class ListAdapter extends RecyclerView.Adapter<ViewHolder> {

        @NonNull
        @Override
        public ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new ViewHolder(LayoutInflater.from(SummaryListActivity.this)
                    .inflate(R.layout.recycler_item_summary, parent, false));
        }

        @Override
        public void onBindViewHolder(@NonNull ViewHolder holder, int position) {
            SummaryBean.Data item = datasource.get(position);
            holder.tv_1.setText(item.childName);
            holder.tv_2.setText(item.childCardNo);
            holder.tv_3.setText(item.teacherName);
            holder.tv_4.setText(item.summary);
            holder.tv_5.setText(TimeUtils.format(item.createTime));

            if ("guardian".equals(Global.userResponse.data.role)){
                holder.btn_send_sms.setVisibility(View.GONE);
                holder.btn_call.setVisibility(View.GONE);
            }else {
                holder.btn_send_sms.setVisibility(View.VISIBLE);
                holder.btn_call.setVisibility(View.VISIBLE);
            }

            holder.btn_send_sms.setOnClickListener(v -> {
                if (AntiShakeUtils.isInvalidClick(v)) {
                    return;
                }
                clickItem = item;
                PermissionUtils.checkPermission(new String[]{"android.permission.SEND_SMS"}, RESULT_CODE,
                        SummaryListActivity.this::sendSmsByIntent);
            });
            holder.btn_call.setOnClickListener(v -> {
                if (AntiShakeUtils.isInvalidClick(v)) {
                    return;
                }
                Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel://" + item.guardianPhone));
                startActivity(intent);
            });
        }

        @Override
        public int getItemCount() {
            return datasource.size();
        }
    }



    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode == RESULT_CODE && clickItem != null) {
            sendSmsByIntent();
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void sendSmsByIntent() {
        Intent intent = new Intent(Intent.ACTION_SENDTO);
        intent.putExtra("sms_body", clickItem.summary);
        Uri data = Uri.parse("smsto:" + clickItem.guardianPhone);
        intent.setData(data);
        startActivity(intent);
    }

    private class ViewHolder extends RecyclerView.ViewHolder {

        private TextView tv_1;
        private TextView tv_2;
        private TextView tv_3;
        private TextView tv_4;
        private TextView tv_5;
        private Button btn_send_sms;
        private Button btn_call;

        public ViewHolder(@NonNull View itemView) {
            super(itemView);

            tv_1 = itemView.findViewById(R.id.tv_1);
            tv_2 = itemView.findViewById(R.id.tv_2);
            tv_3 = itemView.findViewById(R.id.tv_3);
            tv_4 = itemView.findViewById(R.id.tv_4);
            tv_5 = itemView.findViewById(R.id.tv_5);
            btn_send_sms = itemView.findViewById(R.id.btn_send_sms);
            btn_call = itemView.findViewById(R.id.btn_call);
        }
    }
}
